package com.zhiwei.codesecurity.common.utils;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;

public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static boolean isFileExist(String fileAddress) {
        File file = new File(fileAddress);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    public static void saveFile(String fileAddress, byte [] data) {
        if(data != null){
            File file  = new File(fileAddress);
            if(file.exists()){
                file.delete();
            }
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(data, 0, data.length);
                fos.flush();
                fos.close();
            } catch (Exception ex) {
                logger.info("==========保存文件出现异常!|ex: {}", ex.getMessage());
            }

        }
    }

    /**
     * 压缩成ZIP
     * @param srcDirectory 压缩源文件夹路径
     * @param zipFileAddress 压缩目的文件保存地址
     */
    public static void FileToZip2(String srcDirectory, String zipFileAddress) {
        try {
            File file = new File(srcDirectory);
            ZipFile zipFile = new ZipFile(zipFileAddress);
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

            if (file.isFile()) {
                zipFile.addFile(file, parameters);
            } else {
                zipFile.addFolder(srcDirectory, parameters);
            }

        } catch (Exception ex) {
            logger.info(">>>>>>>>压缩异常出错: {}", ex.getMessage());
            return;
        }
    }

    /**
     * 解压缩方法
     * @param zipFileAddress 压缩文件名(需要解压缩的zip包)
     * @param dstPath 解压目标路径
     */
    public static void ZipToFile2(String zipFileAddress, String dstPath) {
        try {
            File file = new File(dstPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            ZipFile zipFile = new ZipFile(zipFileAddress);
            if (!zipFile.isValidZipFile()) {
                logger.error(">>>>>>>>>>>>>压缩文件不合法:{}", zipFileAddress);
                return;
            }

            zipFile.extractAll(dstPath);
        } catch (Exception ex) {
            logger.info(">>>>>>>>解压缩异常出错: {}", ex.getMessage());
            return;
        }
    }

    /**
     * 删除指定文件夹下所有文件（包括该文件夹也一并删除）
     * @param path
     * @return
     */
    public static boolean deleteFolder(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return  false;
        }

        if (file.isFile()) {
            file.delete();
            return true;
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                String rootPath = files[i].getAbsolutePath();
                deleteFolder(rootPath);
            }
            file.delete();
            return true;
        }
    }

    /**
     *
     * @param path
     * @param fileNameList
     */
    public static void deleteFiles(String path, List<String> fileNameList) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }

        if (!file.isDirectory()) {
            return;
        }

        File[] files = file.listFiles();
        File tempFile;
        for (int i = 0; i < files.length; i++) {
            tempFile = files[i];
            if (tempFile.isFile() && fileNameList.contains(tempFile.getName())) {
                tempFile.delete();
            } else {
                deleteFiles(tempFile.getAbsolutePath(), fileNameList);
            }
        }
    }

    public static void main( String[] args ) {
//        FileUtils.FileToZip("D:\\scan_report", "D:\\zhangxian.zip", true);
//        FileUtils.ZipToFile("D:\\zhangxian.zip", "E:\\self-code");
//        FileUtils.ZipToFile2("D:\\local\\codesecurity-service.zip", "E:\\zhangxian");
//        FileUtils.deleteFolder("D:\\deleteFolder\\test1");
//        List<String> fileList = new ArrayList<>();
//        fileList.add("aa.doc");
//        fileList.add("bb.doc");
//        FileUtils.deleteFiles("D:\\deleteFolder", fileList);
    }
}
